import { Component, Prop, Vue, Emit, Watch } from 'vue-property-decorator'
import styles from '../NewApply/ApplyDetail.less'
import sealStyle from './RevokeSeal.less'
import DetailItem from '@/components/DetailItem'
import { IStatus } from '../../lib/sealFormat'
import Upload from '@/components/Upload'
import ImagePreview from '@/components/ImagePreview'
import { ElForm } from 'element-ui/types/form'
import OptionLine from '@/components/OptionLine'

export interface IRevokeSealData {
  agentName: string
  agentMobileDes: string
  agentLicenseNumberDes: string
  agentMobile: string
  agentLicenseNumber: string
  agentLicenseType: number
  reason?: string
  reasonType: number
  fileKey?: string
  url?: string
  sealSn: string
  sealApplyId: number
  reasonContent?: string
}

const sealData: IRevokeSealData = {
  agentName: '',
  agentLicenseType: 1,
  agentMobile: '',
  agentLicenseNumber: '',
  agentLicenseNumberDes: '',
  agentMobileDes: '',
  reason: '',
  reasonType: 1,
  fileKey: '',
  url: '',
  sealSn: '',
  sealApplyId: 0,
  reasonContent: '',
}

const reasonList: any[] = [
  { id: 1, value: '虚假注册' },
  { id: 2, value: '单位调整或注销' },
  { id: 3, value: '印章丢失' },
  { id: 4, value: '其他情况' },
]

const filterReasonValue = (id: number) => {
  return (reasonList.filter((item: any) => item.id === id)[0] || {}).value || ''
}

const filterReasonId = (value: string) => {
  return (
    (reasonList.filter((item: any) => item.value === value)[0] || {}).id || 4
  )
}

const formLabelWidth3: string = '48px'
const formLabelWidth4: string = '60px'
const formLabelWidth5: string = '84px'
const formLabelWidth6: string = '96px'
const formLabelWidth7: string = '120px'
const formLabelWidth8: string = '72px'
const fileTypes = [
  'image/jpeg',
  'image/jpg',
  'image/png',
  'image/bmp',
  'image/gif',
]
const fileSizeLimit = 10
const detailData: any = [
  {
    title: '申请吊销印章范围',
    single: true,
    child: [
      {
        key: 'sealName',
        colLength: 16,
        labelWidth: formLabelWidth7,
        label: '申请吊销电子印章名称',
        content: '',
      },
      {
        key: 'startTime',
        colLength: 16,
        labelWidth: formLabelWidth6,
        label: '电子印章启用时间',
        content: '',
      },
      {
        key: 'endTime',
        colLength: 16,
        labelWidth: formLabelWidth6,
        label: '电子印章终止时间',
        content: '',
      },
    ],
  },
  {
    title: '用章机构基本信息',
    child: [
      {
        key: 'organizeName',
        labelWidth: formLabelWidth3,
        label: '机构名称',
        content: '',
      },
      {
        key: 'organizeType',
        labelWidth: formLabelWidth8,
        label: '机构类型',
        content: '',
      },
      {
        key: 'organizeCardType',
        label: '证照类型',
        labelWidth: formLabelWidth3,
        content: '',
      },
      {
        key: 'organizeCardId',
        label: '证照号码',
        labelWidth: formLabelWidth8,
        content: '',
      },
      // { key: "organizeLevel", label: "行政等级", labelWidth: formLabelWidth3, content: "" }
    ],
  },
]

const lastDetail = [
  {
    title: '经办人基本信息',
    child: [
      {
        key: 'agentName',
        label: '经办人姓名',
        labelWidth: formLabelWidth4,
        content: '',
      },
      {
        key: 'agentMobileDes',
        label: '经办人手机号',
        labelWidth: formLabelWidth8,
        content: '',
      },
      {
        key: 'agentLicenseTypeName',
        label: '经办人证件类型',
        labelWidth: formLabelWidth5,
        content: '',
      },
      {
        key: 'agentLicenseNumberDes',
        label: '经办人证件号',
        labelWidth: formLabelWidth8,
        content: '',
      },
    ],
  },
]

const rules = {
  agentName: [
    { required: true, message: '经办人姓名不能为空', trigger: 'change' },
  ],
  agentMobileDes: [
    { required: true, message: '经办人手机号不能为空', trigger: 'change' },
  ],
  agentLicenseType: [
    { required: true, message: '经办人证件类型不能为空', trigger: 'change' },
  ],
  agentLicenseNumberDes: [
    { required: true, message: '经办人证件号码不能为空', trigger: 'change' },
  ],
  reason: [
    { required: true, message: '吊销原因不能为空', trigger: 'change' },
    { max: 255, message: '不能超过255个字符', trigger: 'change' },
  ],
}

@Component({})
export default class RevokeSeal extends Vue {
  @Prop({ default: '吊销印章申请' }) private title!: string
  @Prop({}) private data!: any
  @Prop({ default: false }) private visible!: boolean
  @Prop({ default: false }) private saveLoading!: boolean
  @Prop({ default: false }) private isEdit!: boolean
  @Prop({ default: '' }) private uploadUrl!: string
  @Prop({ default: false }) private showTimeline!: boolean
  @Prop({}) private sealOption!: any[]
  private sealUrl = ''
  private detailData = []

  private sealData: IRevokeSealData = {
    agentName: '',
    agentLicenseType: 1,
    agentMobile: '',
    agentLicenseNumber: '',
    agentLicenseNumberDes: '',
    agentMobileDes: '',
    reason: '',
    reasonType: 1,
    fileKey: '',
    sealSn: '',
    sealApplyId: 0,
  }

  private formLabelWidth1 = '50px'
  private formLabelWidth2 = '84px'
  private formLabelWidth3 = '60px'

  private imgVisible = false

  private file: any = {
    status: 'init',
  }

  protected render(h: any) {
    return (
      <div class={{ [styles.sealDetail]: true }}>
        <el-dialog
          title={this.title}
          custom-class="custom-dialog"
          width={'700px'}
          close-on-click-modal={false}
          close-on-press-escape={false}
          visible={this.visible}
          {...{
            on: { 'update:visible': this.visibleChange },
          }}
        >
          <el-form
            hide-required-asterisk
            class={styles.sealForm}
            {...{ props: { model: this.sealData } }}
            ref="revokeForm"
            rules={rules}
          >
            {this.detailData &&
              this.detailData.map((item: any, index: number) => (
                <DetailItem
                  class={styles.detailItem}
                  key={index}
                  single={item.single}
                  data={item.child}
                  title={item.title}
                />
              ))}
            {this.isEdit ? (
              <div class={{ [sealStyle.detailForm]: true }}>
                <p class={styles.panel}>
                  <span class={styles.required}>*</span>吊销原因
                </p>
                <div class="pl20 pr30">
                  <el-radio-group v-model={this.sealData.reasonType}>
                    {/* <el-radio label={1}>Ukey签章</el-radio>
                    <el-radio label={2}>云签章</el-radio> */}
                    {reasonList &&
                      reasonList.map((item: IStatus, i: number) => (
                        <el-radio key={`use${i}`} label={item.id}>
                          {item.value}
                        </el-radio>
                      ))}
                  </el-radio-group>
                  {this.sealData.reasonType === 4 && (
                    <el-form-item prop="reason" class="ml10" label-width="0">
                      <el-input
                        type="textarea"
                        rows={3}
                        placeholder="请输入吊销原因"
                        v-model={this.sealData.reason}
                      />
                    </el-form-item>
                  )}
                </div>
                <p class={styles.panel}>吊销来源</p>
                <div class={sealStyle.uploadContent}>
                  <Upload
                    file={this.file}
                    progress={this.fileProgress}
                    action={this.uploadUrl}
                    success={this.uploadSuccess}
                    error={this.uploadError}
                    preview={this.preview}
                    content="上传证明材料表"
                    beforeUpload={this.beforeUpload}
                  />
                  <div class={sealStyle.tips}>
                    上传须知:
                    <br /> 1、图片按照A4纸大小扫描，像素300dpi <br />
                    2、格式须为PNG/JPG/BMP/JPEG/GIF
                  </div>
                </div>
                {this.showTimeline && (
                  <OptionLine
                    class={styles.optionLine}
                    sealOption={this.sealOption}
                    panelTitle="吊销申请信息"
                  />
                )}
              </div>
            ) : (
              <div class={{ [sealStyle.detailForm]: true, mt15: true }}>
                <p class={styles.panel}>吊销原因</p>
                <div class="pl30 pr30">{this.sealData.reasonContent}</div>
                {this.sealData.url && <p class={styles.panel}>吊销来源</p>}
                {this.sealData.url && (
                  <div class="thumbnail" onClick={this.preview}>
                    <div class="hover-blank">
                      <img src={require('@/assets/preview.png')} />
                    </div>
                    <img src={this.sealData.url} />
                  </div>
                )}
                {this.showTimeline && (
                  <OptionLine
                    class={styles.optionLine}
                    sealOption={this.sealOption}
                    panelTitle="吊销申请信息"
                  />
                )}
              </div>
            )}
          </el-form>
          {this.isEdit ? (
            <div slot="footer">
              <el-button
                disabled={this.saveLoading}
                onClick={() => {
                  this.save(false)
                }}
              >
                仅保存
              </el-button>
              <el-button
                type="primary"
                class={[
                  {
                    'btn-primary': true,
                    'btn-primary-hover': this.validField(),
                  },
                ]}
                disabled={this.saveLoading}
                onClick={() => {
                  this.save(true)
                }}
              >
                保存并提交审核
              </el-button>
            </div>
          ) : (
            <div slot="footer">
              <el-button
                disabled={this.saveLoading}
                onClick={() => {
                  this.$emit('visibleChange', false)
                }}
              >
                关闭
              </el-button>
            </div>
          )}
        </el-dialog>
        <ImagePreview
          visible={this.imgVisible}
          title="证明材料预览"
          url={this.file.url}
          onVisibleChange={(val: boolean) => {
            this.imgVisible = val
          }}
        />
      </div>
    )
  }

  @Emit('visibleChange')
  private visibleChange(val: boolean) {
    return val
  }

  @Watch('visible')
  private visibleHandler(val: boolean) {
    if (val && this.data) {
      const itemData = detailData.concat(lastDetail)
      itemData.forEach((detail: any) => {
        detail.child.forEach((item: any) => {
          item.content = this.data[item.key]
        })
      })
      this.sealData = Object.assign({}, sealData, this.data)
      this.sealData.reasonType = filterReasonId(
        this.sealData.reasonContent || ''
      )
      if (this.sealData.reasonType === 4) {
        this.sealData.reason = this.sealData.reasonContent
      }
      this.detailData = itemData
      if (!!this.sealData.fileKey) {
        this.file = Object.assign(
          {},
          {
            name: '证明材料表',
            status: 'done',
            size: 0,
            url: this.sealData.url,
          }
        )
      } else {
        this.file = {}
      }
    }
    this.$nextTick(() => {
      this.$refs.revokeForm && (this.$refs.revokeForm as ElForm).clearValidate()
    })
  }

  private fileProgress(event: any, file: any, fileList: any[]) {
    this.file = Object.assign(
      {},
      {
        name: file.name,
        status: 'upload',
        size: file.size,
        precent: parseInt(file.percentage),
      }
    )
  }

  private uploadSuccess(response: any, file: any, fileList: any[]) {
    if (response.errCode === 0) {
      this.file = Object.assign(
        {},
        {
          name: file.name,
          status: 'done',
          size: file.size,
          url: URL.createObjectURL(file.raw),
        }
      )
      this.sealData.fileKey = response.data.fileKey
    } else {
      this.file = {}
      this.sealData.fileKey = ''
      this.sealData.url = ''
      this.$message.error(response.msg)
    }
  }

  private validField() {
    return (
      !!this.sealData.agentLicenseType &&
      !!this.sealData.agentName &&
      !!this.sealData.agentLicenseNumber &&
      !!this.sealData.agentMobile &&
      ((this.sealData.reasonType === 4 && !!this.sealData.reason) ||
        this.sealData.reasonType !== 4)
    )
  }

  private uploadError(err: any, file: any, fileList: any[]) {
    this.file = {}
    this.sealData.fileKey = ''
    this.sealData.url = ''
    this.$message.error('文件上传失败')
  }

  private beforeUpload(file: any) {
    const isJPG =
      fileTypes.filter(
        (item: string) => item === (file.type || '').toLowerCase()
      ).length > 0
    const isLimit = file.size / 1024 / 1024 < fileSizeLimit
    if (!isJPG) {
      this.$message.error('申请表只能是 JPG/PNG/BMP/JPEG/GIF 格式。')

      return false
    }
    if (!isLimit) {
      this.$message.error(`申请表大小不能超过${fileSizeLimit}MB。`)

      return false
    }
    this.file = Object.assign(
      {},
      { name: file.name, status: 'upload', size: file.size, precent: 0 }
    )
  }

  private preview() {
    this.imgVisible = true
  }

  private save(flag: boolean) {
    ;(this.$refs.revokeForm as ElForm).validate((val: boolean) => {
      if (val) {
        const data = Object.assign({}, this.sealData, {
          reason:
            this.sealData.reasonType === 4
              ? this.sealData.reason
              : filterReasonValue(this.sealData.reasonType),
        })
        if (flag) {
          this.$emit('saveAndSubmit', data)
        } else {
          this.$emit('save', data)
        }
      }
    })
  }
}
